<?php
/*
 * Project Name	: 打酱油的短链接生成器
 * Project Date	: 2014-01-01
 * File Name	: index.php
 * File Create	: 2014-01-01
 * Last Update	: 2014-01-02
 * Author 		: 海蓝
 */
/**************************************************************
 *                                                            *
 * This file is part of SkywindShortLink.                     *
 *                                                            *
 * SkywindShortLink is free project; you can redistribute it  *
 * and/or modify it under the terms of the GNU General Public *
 * License as published by the Free Software Foundation;      *
 * either version 3 of the License, or any later version.     * 
 *                                                            *
 **************************************************************/
require ('dbConnect.class.php');

error_reporting(E_ALL ^ E_DEPRECATED);

$charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
//----define Charbase------

$linkLen = 5;
//----define link length----

$action = isset($_REQUEST['url'])?"creat":"redirect";
//$action = "creat";
//-----switcher-----

$valid = "/(http|https|ftp|file){1}(:\/\/)?([\da-z-\.]+)\.([a-z]{2,6})([\/\w \.-?&%-=]*)*\/?/";
//----valid regx----

switch ($action) {
	case 'creat':  //generate short link
		
		//$url="http://kanade.me";
		$url = $_REQUEST['url'];
		$dir = dirname($_SERVER['PHP_SELF']);

		if(!preg_match($valid, $url))
			die("{\"result\":\"err\",\"err\":\"Invalid URL\"}");
		$db = new dbConnect();
		
		if($res = $db->getOneByUrl($url))
			die("{\"result\":\"exist\",\"count\":\"{$res["count"]}\",\"url\":\"{$_SERVER['HTTP_HOST']}{$dir}/{$res["sUrl"]}\"}");

		$succeed = false;
		$retry = 0;
		
		while(!$succeed && $retry < 100000){
			$retry++;
			
			$sUrl = "";
			for($i = 0 ; $i < $linkLen ; $i++){
				$sUrl .= $charSet[rand(0,strlen($charSet) - 1)];
			}
			if($db->existUrl($sUrl))continue;
			$succeed = true;
		}
		
		if(!$succeed)die("\"result\":\"err\",\"No More Resource\"}");

		$db->insertOne($sUrl,$url);
		echo "{\"result\":\"success\",\"url\":\"{$_SERVER['HTTP_HOST']}{$dir}/$sUrl\"}";
		exit();
	
	case 'redirect':
		$sUrl = isset($_REQUEST["sUrl"])?$_REQUEST["sUrl"]:'';
		$db = new dbConnect();
		$res = $db->getOneByShortUrl($sUrl);
		if($res)
			header("location:{$res["url"]}");
		//var_dump($res);
		break;
}
?>
<strong>打酱油的短链接生成页->施工现场</strong>
<br />
<strong>正在等待某前端大大的代码~</strong>
<br />
<strong>开源的项目 托管于<a href="https://code.google.com/p/skywindshortlink/">https://code.google.com/p/skywindshortlink/</a></strong>